package com.uzai.console.service.sysmenu.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.sysmenu.SysMenuInfoDto;
import com.uzai.console.entity.SysMenu;
import com.uzai.console.mapper.SysMenuMapper;
import com.uzai.console.service.sysmenu.SysMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author liuqi
 * @date 2021年09月11日 14:12
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    private Logger logger = LoggerFactory.getLogger(SysMenuServiceImpl.class);

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public void uploadSysMenu(SysMenuInfoDto sysMenuInfoDto) {
        if(StringUtils.isBlank(sysMenuInfoDto.getAppKey())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "平台KEY不能为空");
        }
        if(StringUtils.isBlank(sysMenuInfoDto.getRoutes())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "平台KEY不能为空");
        }

        if(StringUtils.isBlank(sysMenuInfoDto.getPassword())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证密码");
        }

        if(!"e9ad597a-0021-4e37-9706-c1ea96ca2ad7".equals(sysMenuInfoDto.getPassword())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "验证密码不正确");
        }

        SysMenu sysMenu = sysMenuMapper.selectByAppKey(sysMenuInfoDto.getAppKey());

        Integer now = DateUtil.getNowTime();

        //新增
        if(sysMenu == null){
            sysMenu = new SysMenu();
            BeanUtils.copyProperties(sysMenuInfoDto, sysMenu);
            sysMenu.setId(IdWorker.getId());
            sysMenu.setCreateTime(now);
            sysMenu.setUpdateTime(now);
            sysMenuMapper.insert(sysMenu);
        }else{//修改
            sysMenu.setIcon(sysMenuInfoDto.getIcon());
            sysMenu.setUrl(sysMenuInfoDto.getUrl());
            sysMenu.setRemark(sysMenuInfoDto.getRemark());
            sysMenu.setName(sysMenuInfoDto.getName());
            sysMenu.setRoutes(sysMenuInfoDto.getRoutes());
            sysMenu.setpKey(sysMenuInfoDto.getpKey());
            sysMenu.setUpdateTime(now);
            sysMenuMapper.updateById(sysMenu);
        }
    }

    /**
     * 递归解析菜单JSONObject，获取API接口转换成map
     * @param jsonObject
     * @return
     */
    public Map<String,JSONObject> analysis(JSONObject jsonObject, Map<String,JSONObject> result){

        try{

            Set<String> keys = jsonObject.keySet();
            if(keys.contains("type")){
                if("api".equals(jsonObject.getString("type"))){
                    JSONObject jsonObjectDmp = new JSONObject();
                    jsonObjectDmp.put("auth",jsonObject.getString("auth"));
                    jsonObjectDmp.put("pKey",jsonObject.getString("pKey"));
                    result.put(jsonObject.getString("path"), jsonObjectDmp);
                }
            }

            for (String key : keys) {
                Object value = jsonObject.get(key);
                if(value instanceof JSONObject){
                    JSONObject valueJsonObject= (JSONObject) value;
                    analysis(valueJsonObject, result);
                }else if(value instanceof JSONArray){
                    JSONArray jsonArray = (JSONArray) value;
                    if(jsonArray.size() > 0){
                        analysisJSONArray(jsonArray, result);
                    }
                }
            }

            //modify by 20231211
//            keys.parallelStream().forEach(key->{
//                Object value = jsonObject.get(key);
//                if(value instanceof JSONObject){
//                    JSONObject valueJsonObject= (JSONObject) value;
//                    analysis(valueJsonObject, result);
//                }else if(value instanceof JSONArray){
//                    JSONArray jsonArray = (JSONArray) value;
//                    if(jsonArray.size() == 0){
//                        return;
//                    }
//                    analysisJSONArray(jsonArray, result);
//                }
//            });
        }catch (Exception e){
            logger.error("角色授权JSON解析出错！routes={}", jsonObject.toJSONString());
        }

        return result;
    }


    /**
     * 递归解析JSONArray
     * @param jsonArray
     * @param result
     */
    public  void analysisJSONArray(JSONArray jsonArray, Map<String,JSONObject> result){

        for (Object json : jsonArray) {
            if(json instanceof JSONObject){
                JSONObject valueJsonObject= (JSONObject) json;
                analysis(valueJsonObject, result);
            }else if(json instanceof JSONArray){
                JSONArray tmpJsonArray = (JSONArray) json;
                if(tmpJsonArray.size() >= 0){
                    analysisJSONArray(tmpJsonArray, result);
                }
            }
        }

        //modify by 20231211
//        jsonArray.parallelStream().forEach(json->{
//            if(json instanceof JSONObject){
//                JSONObject valueJsonObject= (JSONObject) json;
//                analysis(valueJsonObject, result);
//            }else if(json instanceof JSONArray){
//                JSONArray tmpJsonArray = (JSONArray) json;
//                if(tmpJsonArray.size() == 0){
//                    return;
//                }
//                analysisJSONArray(tmpJsonArray, result);
//            }
//        });
    }


}
